<?php
/**
 * Copyright (c) 2006, PORTALIER Julien
 * 
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 * 
 * @package      FeatherCMS
 * @subpackage   Components
 * @copyright    Copyright (c) 2006, Julien PORTALIER
 * @link         http://julien.portalier.com
 * @license      http://www.opensource.org/licenses/mit-license.php The LGPL License
 */

class LockerComponent
{
	protected $controller;
	protected $session;
	
	function startup(Controller $controller)
	{
		$this->controller = $controller;
#		$this->session = $controller->session;
#		$this->set($this->controller->here);
	}
	
	function lock($resource=null, $mesg=null)
	{
		if (!is_null($resource))
			$this->set($resource);
		
		if ($this->check())
		{
			// locks resource
#			$str = uniqid();
#			$this->session->write($this->sess, $str);
#			file_put_contents($this->file, $str);
			file_put_contents($this->file, $this->controller->acl->id);
		}
		else
		{
			// resource is already locked
			$referer = getReferer();
			if (preg_match('{'.rtrim($this->controller->here, '/').'$}', $referer))
				$referer = '/';
				
#			if ($referer == PROTOCOL.env('HTTP_HOST').'/'.rtrim($this->controller->here, '/'))
#				$referer = '/';
			$this->controller->flash(
				empty($mesg) ? _('Someone is already editing this resource, please try again later.') : $mesg,
				$referer
			);
		}
	}
	
	function unlock($resource=null)
	{
		if (!is_null($resource))
			$this->set($resource);
#		$this->session->delete($this->sess);
		@unlink($this->file);
	}
	
	function check($resource=null)
	{
		if (!is_null($resource))
			$this->set($resource);
		
		// is resource locked?
		if (file_exists($this->file))
		{
			// is lock valid?
			if (filemtime($this->file) - time() + 20 * 60 > 0)
#				return (file_get_contents($this->file) == $this->session->read($this->sess));
				return (file_get_contents($this->file) == $this->controller->acl->id);
			
			// lock has expired
			$this->unlock();
		}
		
		return true;
	}
	
	function set($resource)
	{
		$this->md5  = md5($resource);
		$this->sess = "Lock.{$this->md5}";
		$this->file = APP.'tmp'.DS.'locks'.DS.$this->md5;
	}
}
?>